<template>

  <section id="mysql-manager-select">
  <el-row :gutter="20" >
    <el-col :span="4" >
      <!--<div style="margin-top: 10px;margin-bottom: 10px ;font-size:120%;">{{this.$route.params.instance}}</div>-->
      <el-tag size="small" type="default" style="margin-bottom: 5px"><i class="iconfont" style="color: red">&#xe604;</i>    {{this.$route.params.instance}}</el-tag>
      <el-select v-model="thisDb" placeholder="请选择数据库" style="width: 100%" size="small" @focus="chooseDbs" @change="getTables">
        <el-option v-for="db in this.databaseList " :label=db.name :value=db.name></el-option>
      </el-select>
      <el-button type="success" style="width: 100% ; margin-top: 10px;margin-bottom: 10px" @click="getTables" size="mini">刷新</el-button>

      <el-table
              :data="tableList"
              height="670"
              border
              style="width: 100%">
        <el-table-column

                label="表名"
                style="width: 100%">
          <template slot-scope="scope">
            <el-dropdown trigger="click" style="width: 100%">
              <div class="el-dropdown-link">
                <el-col :span="20">{{scope.row.name}}</el-col>
                <el-col :span="2"><i class="el-icon-arrow-down el-icon--right" ></i></el-col>

              </div>
              <el-dropdown-menu slot="dropdown">
                <el-dropdown-item>表结构</el-dropdown-item>
                <el-dropdown-item>索引</el-dropdown-item>
                <el-dropdown-item>锁分析</el-dropdown-item>
                <el-dropdown-item disabled>重命名</el-dropdown-item>
                <el-dropdown-item disabled>删除</el-dropdown-item>
              </el-dropdown-menu>
            </el-dropdown>


          </template>
        </el-table-column>

      </el-table>

    </el-col>

    <el-col :span="17" >

      <!--<div style="margin-top: 10px;margin-bottom: 10px ;font-size:120%;text-align: left">查询语句（select）</div>-->
      <el-tag size="small" type="default" style="margin-bottom: 5px">查询语句  (ddl/dml语句被后台省略 !! )</el-tag>
      <edit-mysql></edit-mysql>
        <el-row style="margin-top: 5px;margin-bottom: 5px">
          <el-button type="default" size="mini" @click="doChooseSql">执行选中SQL</el-button>
          <el-button type="primary" size="mini" @click="doAllSql">全部执行</el-button>
          <el-button type="success" size="mini" @click="exportTable">导出结果</el-button>
        </el-row>


      <el-tabs style="margin: 0 ; font-size: 3px"  size="mini"  type="border-card"  @tab-click="setExportData">
        <el-tab-pane  v-for="(head,index) in this.tableHeader" :index="index">
          <span slot="label">
            <i class="iconfont" style="color: red">&#xec6d;</i>

            result{{index}}

          </span>

          <el-table

                  :data="tableResutl[index].slice((currpage - 1) * pagesize, currpage * pagesize)"
                  border
                  :row-style="rowHeigthSetting"

                  header-cell-class-name="tab-header"
                  style="width: 100%">
            <el-table-column
                    v-for="col in head"
                    :prop="col"
                    :label="col"
            >
            </el-table-column>

          </el-table>

          <el-pagination
                  small
                  background
                         layout="prev, pager, next, sizes, total"
                         :page-sizes="[5, 10, 15, 20,50,100,500]"
                         :page-size="pagesize"
                         :total="tableResutl[index].length"
                         @current-change="handleCurrentChange"
                         @size-change="handleSizeChange"

          >
          </el-pagination>
        </el-tab-pane>

      </el-tabs>



    </el-col>




  </el-row>

  </section>

</template>

<script>
    import { getDbLists,getTableList,doSelect } from '../../../api/api'
    import editMysql from '../../../components/edit/mysqlcode.vue'
    import $ from 'jquery' //引入jquery 检测输入yaml内容是否格式错误
    //import VueCodemirror from 'vue-codemirror'
  export default {
      data()  {

          return {
              databases: [
              ],
              thisDb: this.$route.query.dbname,
              tableList: [
              ],
              tableHeader: [],
              tableResutl: [],
              pagesize: 10,
              currpage: 1,
              databaseList: ["a","b","c"],
              tableNum : 2 ,
              exportIndex: 0,
              exportTableHeader: [],
              exportTableData: [],




          }
      },
      methods: {
          handleCurrentChange(cpage) {
              this.currpage = cpage;
          },
          handleSizeChange(psize) {
              this.pagesize = psize;
          },

          exportTable() {
              console.log("debug export table ")
              this.exportTableHeader = this.tableHeader[this.exportIndex]
              this.exportTableData = this.tableResutl[this.exportIndex]
              require.ensure([], () => {
                  const { export_json_to_excel } = require('../../../vendor/Export2Excel');
                  const tHeader = this.exportTableHeader
                  const filterVal = this.exportTableHeader
                  const list = this.exportTableData;
                  const data = this.formatJson(filterVal, list);
                  export_json_to_excel(tHeader, data, 'result' + this.exportIndex);
              })
          },
          formatJson(filterVal, jsonData) {
              return jsonData.map(v => filterVal.map(j => v[j]))
          },
          chooseDbs(){
              var param = {instance: this.$route.params.instance}
              getDbLists(param).then((res) => {
                      console.log(res.data.dblist)
                      //this.addSqlJob.dbChoice = res.data.dblist
                      this.databaseList = res.data.dblist

                  }
              )
          },
          getTables(){

              var cm = $(".mysqlcode  .CodeMirror")[0].CodeMirror;  //怕多个codemirror引起的混乱
              var doc = cm.getDoc();
              doc.setValue("")      //数据库切换时，删除编辑框的值

              //var param = {instance: this.$route.params.instance,dbname:this.$route.query.dbname}
              var param = {instance: this.$route.params.instance,dbname:this.thisDb}
              getTableList(param).then((res) => {
                  console.log(res.data.tableList)
                  this.tableList = res.data.tableList

              })
          },
          doChooseSql() {
              console.log("debug choose sql")
              var cm = $(".mysqlcode  .CodeMirror")[0].CodeMirror;  //怕多个codemirror引起的混乱
              var doc = cm.getDoc();
              //console.log(doc.getValue().toString())
              console.log(doc.getSelection().toString())
              console.log(this.$route.params.instance)
              console.log(this.thisDb)
              var para = { instance: this.$route.params.instance,dbname:this.thisDb , statement: doc.getSelection().toString()  };
              doSelect(para).then((res) => {
                  console.log(res)
                  if (res.code === 200) {
                      this.tableHeader = res.finalheader
                      this.tableResutl = res.finalresult

                  } else if (res.code === 400) {
                          alert(res.error)
                  }


              })
          },
          doAllSql() {
              var cm = $(".mysqlcode  .CodeMirror")[0].CodeMirror;  //怕多个codemirror引起的混乱
              var doc = cm.getDoc();
              //console.log(doc.getValue().toString())
              var para = { instance: this.$route.params.instance,dbname:this.thisDb , statement: doc.getValue().toString()  };
              doSelect(para).then((res) => {
                  if (res.code === 200) {
                      this.tableHeader = res.finalheader
                      this.tableResutl = res.finalresult

                  } else if (res.code === 400) {
                      alert(res.error)
                  }
              })
          },
          setExportData(tab, event) {
              console.log("asdasdasdasd")
              console.log(tab.index)
              this.exportIndex = tab.index

          },

          headerStyle({ row, rowIndex}){
              return "height:10px;color:#0099FF;background-color: #FAFAFA;"
          },

          testbtn(){
              alert("nimabide")
          }

      },
      computed: {
          rowHeigthSetting: function (row,index) {
              return {"height":"3.1vh;font-weight: bolder;"}
          }
      },
      components: {
          editMysql,
      },
      mounted() {
          //console.log("debug here" , this.$route.params.name)
          this.getTables();
      },

  }
</script>

<style>
  #mysql-manager-select .el-header {
    background-color: #B3C0D1;
    color: #333;
    line-height: 60px;
  }

  #mysql-manager-select .el-aside {
    color: #333;
  }
  #mysql-manager-select .el-table td{
    padding: 0;
  }
  #mysql-manager-select .el-pagination{
    text-align: right;
  }
  #mysql-manager-select .select-result  .el-tabs__item {
    font-size: 10px !important;
    color: red;
  }
  #mysql-manager-select .select-result .is-top {
    height: 30px;
  }
  #mysql-manager-select .select-result .el-tabs__header{
    margin: 0px !important;
    height: 50%;
  }

  #mysql-manager-select .el-tabs__active-bar {
    display: none;
  }

  #mysql-manager-select .el-dropdown-link {
    cursor: pointer;
    color: #409EFF;
  }
  #mysql-manager-select .el-icon-arrow-down {
    font-size: 12px;

  }
  #mysql-manager-select .el-tabs--border-card>.el-tabs__content {
    padding: 0px;
  }

  #mysql-manager-select .tab-header {
    color: black;
    font-size: 15px;
    font-weight: bold;
  }

  #mysql-manager-select .el-table td, .el-table th {
    padding: 2px;
  }

  #mysql-manager-select .result-download {
    cursor: url("../../../assets/img/download3.jpg"),pointer;
  }

</style>